/**
 * 
 */
package sailing.listener;

import java.util.List;

import javax.swing.SwingUtilities;

import cjlite.logger.Logger;
import cjlite.utils.Lists;

/**
 * @author kevin
 * 
 */
public final class AppListenerManager {
	private static Logger logger = Logger.thisClass();

	private static AppListenerManager instance;

	private List<DataListener> dataListenerList = Lists.newCopyOnWriteArrayList();

	private AppListenerManager() {
	}

	public static AppListenerManager getInstance() {
		if (instance == null) {
			instance = new AppListenerManager();
		}
		return instance;
	}

	public void frieDateChanged() {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				insidefrieDateChanged();
			}
		});

	}

	protected void insidefrieDateChanged() {
		for (DataListener dataListener : dataListenerList) {
			try {
				dataListener.dataChanged();
			} catch (Throwable e) {
				logger.error("error on first data change listener {0}", e, dataListener.getClass().getName());
			}
		}
	}

	public void addDataListener(DataListener dataListener) {
		if (dataListener == null) {
			logger.error("You are going to add a NULL listener,Pls be carefully");
			return;
		}
		dataListenerList.add(dataListener);
	}

	public void removeDataListener(DataListener dataListener) {
		if (dataListener == null) {
			return;
		}
		dataListenerList.remove(dataListener);
	}

	public void frieDateChanged(final AppEvent newEvent) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				insidefrieDateChanged(newEvent);
			}
		});
	}

	protected void insidefrieDateChanged(AppEvent newEvent) {
		for (DataListener dataListener : dataListenerList) {
			try {
				if (newEvent.getListenerClass().equals(dataListener.getClass())) {
					dataListener.dataChanged();
				}
			} catch (Throwable e) {
				logger.error("error on first data change listener {0}", e, dataListener.getClass().getName());
			}
		}
	}

}
